package com.itheima.api.homework;

import com.sun.source.tree.NewArrayTree;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 有以下double数组：
 * double[] arr = {0.1,0.2,2.1,3.2,5.56,7.21};
 * 请编程计算它们的总值及平均值(四舍五入保留小数点后2位)
 */
public class Test1 {
    public static void main(String[] args) {
        //声明数组
        double[] arr = {0.1, 0.2, 2.1, 3.2, 5.56, 7.21};
        double sum = getSum(arr);
        System.out.println("总和：" + sum);
        double avg = getAvg(arr, sum);
        System.out.println("平均值为:" + avg);
    }
        //计算平均值方法
    private static double getAvg(double[] arr, double sum) {
        BigDecimal sumBigDecimal = new BigDecimal(sum);
        BigDecimal arrBigDecimal = new BigDecimal(arr.length);
        BigDecimal divide = sumBigDecimal.divide(arrBigDecimal, 2, BigDecimal.ROUND_HALF_UP);
        return divide.doubleValue();
    }



  /*  private static double getAvg(double[] arr) {
        double sum = getSum(arr);
        BigDecimal bigDecimal = BigDecimal.valueOf(sum);
        BigDecimal result = bigDecimal.divide(BigDecimal.valueOf(arr.length),2, RoundingMode.HALF_UP)
            
    }*/

    private static double getSum(double[] arr) {
        BigDecimal bigDecimal = new BigDecimal("0");
        for (int i = 0; i < arr.length; i++) {
            bigDecimal = bigDecimal.add(BigDecimal.valueOf(arr[i]));
        }
        return bigDecimal.doubleValue();
    }
}
